package zhihui.mobile.ui.shop.order;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;


import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zgm.utils.ui.UiTextHeader;

import java.util.List;

import zhihui.mobile.R;
import zhihui.mobile.bean.ilpay.PayResult;
import zhihui.mobile.bean.shop.SkuInfo;
import zhihui.mobile.bean.shop.address.ShoppingAddress;
import zhihui.mobile.bean.shop.sales.CouponInfo;
import zhihui.mobile.bean.wx.WeixinPayInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.manager.pay.PayManager;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.presenter.shop.ShopOrderConfirmPresenter;
import zhihui.mobile.ui.BaseActivity;
import zhihui.mobile.ui.shop.cart.ShoppingCartActivity;
import zhihui.mobile.ui.utils.UiUtils;

/**
 * Created by 张公铭 on 2017/8/17 0017.
 */

public class ShopOrderConfirmActivity extends BaseActivity implements IShopOrderConfirmContract.IShopOrderConfirmView
{
    private ShopOrderConfirmPresenter confirmPresenter = new ShopOrderConfirmPresenter();

    private UiTextHeader mHeader;
    private TextView tv_name;
    private TextView tv_tel;
    private TextView tv_address;
    private RelativeLayout rl_address;
    private ListView lv_shop;
    private TextView tv_num;
    private TextView tv_count;
    private RelativeLayout rl_sales;
    private TextView tv_sales;
    private TextView tv_money;
    private TextView tv_express;
    private TextView tv_sales_price;
    private TextView tv_pay_money;
    private TextView tv_buy;

    private OrderAdapter adapter;
    private Handler mHander;
    private static final int SDK_PAY_FLAG = 1;

    private Dialog shopAddressDialog;
    private IWXAPI api;

    @Override
    public void initView()
    {
        api = WXAPIFactory.createWXAPI(this, Config.WX_APP_ID, true);
        api.registerApp(Config.WX_APP_ID);

        PayManager.wx_pay = 0;

        mHander = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                    case SDK_PAY_FLAG:
                    {
                        PayResult payResult = new PayResult((String) msg.obj);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000"))
                        {
                            showMessage("支付成功");
                            //跳转订单详情界面
                            confirmPresenter.goOrderDetail();
                        } else
                        {
                            // 判断resultStatus 为非"9000"则代表可能支付失败
                            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000"))
                            {
                                showMessage("支付结果确认中");
                                tv_buy.setText("支付确认中");
                                tv_buy.setEnabled(false);

                            } else
                            {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                showMessage("支付失败");
                                tv_buy.setText("重新支付");
                                tv_buy.setEnabled(true);
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        };

        mHeader = (UiTextHeader) findViewById(R.id.shop_order_confirm_header);
        mHeader.setTitle("确认订单");
        mHeader.setLeftBottonIcon(R.drawable.shop_back);
        mHeader.setLeftButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                goBack(ShopOrderConfirmActivity.class);
            }
        });
        mHeader.hindRight();

        tv_name = (TextView) findViewById(R.id.tv_shop_order_confirm_name);
        tv_tel = (TextView) findViewById(R.id.tv_shop_order_confirm_phone);
        tv_address = (TextView) findViewById(R.id.tv_shop_order_confirm_address);
        rl_address = (RelativeLayout) findViewById(R.id.rl_shop_order_confirm_address);
        rl_address.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //显示地址列表
                confirmPresenter.getAddressList();
            }
        });

        lv_shop = (ListView) findViewById(R.id.lv_shop_order_confirm_shops);
        adapter = new OrderAdapter(this);
        lv_shop.setAdapter(adapter);

        tv_num = (TextView) findViewById(R.id.tv_shop_order_confirm_count);
        tv_money = (TextView) findViewById(R.id.tv_shop_order_confirm_all_price);

        rl_sales = (RelativeLayout) findViewById(R.id.rl_shop_order_confirm_sales);
        tv_sales = (TextView) findViewById(R.id.tv_shop_order_confirm_sales);
        rl_sales.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                confirmPresenter.getSalesList();
            }
        });

        tv_count = (TextView) findViewById(R.id.tv_shop_order_confirm_count_price);
        tv_express = (TextView) findViewById(R.id.tv_shop_order_confirm_express);
        tv_sales_price = (TextView) findViewById(R.id.tv_shop_order_confirm_sales_price);

        tv_pay_money = (TextView) findViewById(R.id.tv_shop_order_confirm_price);
        tv_buy = (TextView) findViewById(R.id.tv_shop_order_confirm_buy);
        tv_buy.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (tv_buy.getText().equals("提交订单"))
                {
                    confirmPresenter.createOrder();
                } else
                {
                    showPayDialog();
                }

            }
        });

        confirmPresenter.initData();
    }

    @Override
    protected void parseArgumentsFormIntent(Intent argIntent)
    {
        int salesId = argIntent.getIntExtra("salesId", 0);
        confirmPresenter.getAddOrderInfo().setSalesId(salesId);
    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.shop_order_confirm_activity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[]{confirmPresenter};
    }

    @Override
    protected void onInitPresenter()
    {
        confirmPresenter.init(this, this);
    }

    @Override
    public void updateAddress(ShoppingAddress address)
    {
        if (address == null)
        {
            tv_name.setVisibility(View.GONE);
            tv_tel.setVisibility(View.GONE);
            tv_address.setText("请选择收货地址");
        } else
        {
            tv_name.setVisibility(View.VISIBLE);
            tv_tel.setVisibility(View.VISIBLE);
            tv_name.setText(address.getName());
            tv_tel.setText(address.getTel());
            tv_address.setText(address.getAddress());
            confirmPresenter.getAddOrderInfo().setAddressId(address.getId());
            confirmPresenter.getAddOrderInfo().setCityCode(address.getCitycode());
        }
    }

    @Override
    public void updateSales(CouponInfo couponInfo)
    {
        tv_sales.setText("可用" + ((double) couponInfo.getCoupon() / 100) + "优惠金额");
        tv_pay_money.setText("￥" + ((double) (confirmPresenter.getPay_money() - couponInfo.getCoupon()) / 100));
        confirmPresenter.setPay_money(couponInfo.getCoupon());
    }

    @Override
    public void updateShopList(List<SkuInfo> list)
    {
        adapter.setmList(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void updateShopInfo(int shopCount, double money)
    {
        tv_num.setText("共计" + shopCount + "件商品");
        tv_money.setText("￥" + money);
        tv_pay_money.setText("￥" + money);
        tv_count.setText("￥" + money);
    }

    @Override
    public void showAddressDialog(List<ShoppingAddress> list)
    {
        shopAddressDialog = UiUtils.getShopAddressDalig(this, list, new UiUtils.ISelectAddressListener()
        {
            @Override
            public void refreshView(ShoppingAddress address)
            {
                tv_name.setVisibility(View.VISIBLE);
                tv_tel.setVisibility(View.VISIBLE);
                tv_name.setText(address.getName());
                tv_tel.setText(address.getTel());
                tv_address.setText(address.getAddress());
                confirmPresenter.getAddOrderInfo().setAddressId(address.getId());
                confirmPresenter.getAddOrderInfo().setCityCode(address.getCitycode());
            }
        });
        shopAddressDialog.show();
    }

    @Override
    public void showCouponDialog(List<CouponInfo> list)
    {
        UiUtils.showCouponDialog(this, list, new UiUtils.ISelectCouponListener()
        {
            @Override
            public void refreshView(CouponInfo couponInfo)
            {
                updateSales(couponInfo);
                confirmPresenter.getAddOrderInfo().setDiscountId(couponInfo.getCouponId());
                confirmPresenter.getAddOrderInfo().setCoupon_money(couponInfo.getCoupon());
            }
        });
    }

    @Override
    public void showPayDialog()
    {
        UiUtils.showPayDialog(this, confirmPresenter.getPay_money(), new UiUtils.IPayListener()
        {
            @Override
            public void weixinPay()
            {
                confirmPresenter.weixinPay();
            }

            @Override
            public void ilPay()
            {
                confirmPresenter.ilpay();
            }
        });
    }

    @Override
    public void ilPay(final String data)
    {
        Runnable payRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ShopOrderConfirmActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHander.sendMessage(msg);
            }
        };
        Thread thread = new Thread(payRunnable);
        thread.start();
    }

    @Override
    public void refreshAddressDialog()
    {
        if (shopAddressDialog != null && shopAddressDialog.isShowing())
        {
            shopAddressDialog.dismiss();
            shopAddressDialog = null;
            confirmPresenter.getAddressList();
        }
    }

    @Override
    public void weixinPay(WeixinPayInfo payInfo)
    {
        PayReq payRequest = new PayReq();
        payRequest.appId = Config.WX_APP_ID;
        payRequest.partnerId = payInfo.getPartnerid();
        payRequest.prepayId = payInfo.getPrepayid();
        payRequest.packageValue = payInfo.getPackages();
        payRequest.nonceStr = payInfo.getNoncestr();
        payRequest.timeStamp = payInfo.getTimestamp();
        payRequest.sign = payInfo.getSign();

        boolean result = api.sendReq(payRequest);
        if (!result)
        {
            showMessage("请检查微信是否启动");
        }
    }

    @Override
    public void refreshButtonBuy(int state)
    {
        tv_buy.setEnabled(true);
        tv_buy.setText("提交订单");
        switch (state)
        {
            case -1:
                tv_buy.setEnabled(true);
                tv_buy.setText("重新支付");
                break;
            case 1:
                confirmPresenter.goOrderDetail();
                break;
        }
    }

    @Override
    public void showGoShopCartDialog()
    {
        com.zgm.utils.UiUtils.showDialog(this,"提示","你所选的商品库存不足，请重新下单", "去购物车", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                confirmPresenter.goShopCart(ShopOrderConfirmActivity.this, ShopOrderConfirmActivity.this);
            }
        });
    }
}
